<template>
  <div>
    <yt-crud
      v-bind="options"
      ref="crudRef"
      @onLoad="getData"
      :search-props="{
        showKeyword: true,
        keywordPlaceholder: t('business.order.placeholder.keyword'),
        keywordWidth: 350,
      }"
      :fun-props="{
        exportBtn: true,
        delBtn: false,
        addBtn: false,
        exportPermi: ['business:order:export'],
      }"
      :table-props="{
        index: false,
        selection: true,
        delBtn: false,
        viewBtn: true,
        editBtn: false,
        menuSlot: true,
        menuWidth: 180,

        viewPermi: ['business:order:query'],
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @change="onChange"
      @openBeforeFun="openBeforeFun"
      @exportFun="handleExport"
    >
      <template #leftToolbar>
        <el-dropdown class="mt-[1px]" v-if="multipleSelection.length > 0" v-has-roles="[constants.SUPER_ADMIN_ROLE_KEY]">
          <el-button plain>批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button>
          <template #dropdown>
            <el-dropdown-item icon="Coin">
              <template #default>
                <el-popconfirm :title="t('operate.confirm.batchSettle')" @confirm="handleBatchSettle">
                  <template #reference> {{t('crud.batchSettleText')}} </template>
                </el-popconfirm>
              </template>
            </el-dropdown-item>
          </template>
        </el-dropdown>
      </template>
      <template #rightToolbar> </template>
      <template #menuSlot="scope:any">
        <template v-if="scope.row.state === 'Finished' && scope.row.customerId">
          <div class="menu-btn" v-has-permi="['business:order:settle']">
            <el-tooltip class="box-item" effect="dark" :content="t('business.order.action.settle')" placement="top">
              <el-button link type="primary" icon="Coin" @click="handleSettle(scope.row)" />
            </el-tooltip>
            <div class="el-divider el-divider--vertical"></div>
          </div>
        </template>


        <template v-if="scope.row.debitAmount && scope.row.debitAmount < '0.00'">
          <div class="menu-btn" v-has-roles="[constants.SUPER_ADMIN_ROLE_KEY]">
            <el-tooltip class="box-item" effect="dark" :content="t('business.order.action.debit')" placement="top">
              <el-button link type="primary" icon="ForkSpoon" @click="handleDebit(scope.row)" />
            </el-tooltip>
            <div class="el-divider el-divider--vertical"></div>
          </div>
        </template>
        <template v-if="scope.row.state == 'Processing'">
          <el-dropdown @command="handleOperate" v-has-permi="['business:order:operate']">
            <span class="el-dropdown-link">
              {{t('crud.table.column.operate')}}<el-icon class="el-icon--right"><arrow-down /></el-icon
            ></span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="{ command: 'stopCharge', row: scope.row }">{{t('business.order.action.stopCharge')}}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </template>
      <!--搜索插槽-->
      <template #createTimeSearch="scope:any">
        <el-date-picker
          format="YYYY-MM-DD"
          v-model="scope.row.createTime"
          type="daterange"
          :start-placeholder="t('crud.table.column.startTime')"
          :end-placeholder="t('crud.table.column.endTime')"
          :shortcuts="shortcuts"
        />
      </template>

      <template #keywordSearch="scope:any">
        <el-input v-model="scope.row.keyword" style="width: 310px" :placeholder="t('business.order.placeholder.keyword')" />
      </template>

      <template #username="scope:any">
        <el-tag type="info" size="small">{{scope.row.username}}</el-tag>
      </template>
      <template #chargerDn="scope:any">
        <span>{{scope.row.chargerDn}}</span>
      </template>
      <template #gunNo="scope:any">
        <span>{{scope.row.gunNo}}</span>
      </template>
      <template #startEndTime="scope:any">
        <div>{{scope.row.startTime || '-'}}</div>
        <div>{{scope.row.endTime || '-'}}</div>
      </template>

      <template #chargeMinute="scope:any">
        <span>{{scope.row.chargeMinute || '-'}}</span>
      </template>
      <template #remainMinute="scope:any">
        <span>{{scope.row.remainMinute || '-'}}</span>
      </template>

      <template #totalQuantity="scope:any">
        <span>{{scope.row.totalQuantity || '-'}}</span>
      </template>

      <template #stopReason="scope:any">
        <span
          >{{ te('business.order.stopCode.' + scope.row.stopReason) ? t('business.order.stopCode.' + scope.row.stopReason) : scope.row.stopReason || '-'}}</span
        >
      </template>
      <template #settledAmount="scope:any">
        <template v-if="scope.row.debitAmount && scope.row.debitAmount != '0.00'">
          <el-tooltip :content="(scope.row.debitAmount < 0 ? t('business.order.debitAmount') : t('business.order.surplusAmount'))  + ` ` + scope.row.debitAmount" placement="top">
            <span @click="handleSettleView(scope.row)" :style="{cursor: 'pointer', color: scope.row.debitAmount < 0 ? 'orange' : 'green'}">{{scope.row.settledAmount || '-'}}</span>
          </el-tooltip>
        </template>
        <template v-else>
          <el-button link type="primary" @click="handleSettleView(scope.row)">{{scope.row.settledAmount || '-'}}</el-button>
        </template>
      </template>
      <template #discountAmount="scope:any">
        <span>{{scope.row.discountAmount || '-'}}</span>
      </template>

      <template #parkAmount="scope:any">
        <span v-if="scope.row.state === 'Settled'">{{scope.row.parkAmount}}</span>
        <span v-else>-</span>
      </template>

      <template #orderAmount="scope:any">
        <div v-if="scope.row.orderAmount">
          <el-tooltip
            v-if="scope.row.state === 'Settled'"
            :content="t('business.order.elecAmount') + `: ` + scope.row.elecAmount + ` ` + t('business.order.serviceAmount') +  `: ` + scope.row.serviceAmount + ` ` + t('business.order.parkAmount') +  `: ` + scope.row.parkAmount"
            placement="top"
          >
            <el-button link>{{scope.row.orderAmount}}</el-button>
          </el-tooltip>
          <span v-else>-</span>
        </div>
        <div v-else>-</div>
      </template>

      <template #totalAmount="scope:any">
        <div v-if="scope.row.totalAmount">
          <el-tooltip
            v-if="scope.row.state === 'Finished' || scope.row.state === 'Settled'"
            :content="t('business.order.item.elecAmount') + `: ` + scope.row.elecAmount + ` ` + t('business.order.item.serviceAmount') +  `: ` + scope.row.serviceAmount"
            placement="top"
          >
            <el-button link>{{scope.row.totalAmount}}</el-button>
          </el-tooltip>
          <span v-else>{{scope.row.totalAmount}}</span>
        </div>
        <div v-else>-</div>
      </template>
      <template #state="scope:any">
        <DictTag :options="OrderStateEnum" :value="scope.row.state" />
      </template>
    </yt-crud>
    <Settlement ref="settlementRef" @success="handleSuccess" />
    <Resettle ref="resettleRef" @success="handleSuccess" />
    <Debit ref="debitRef" @success="handleSuccess" />
    <SettleList ref="settleListRef" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import {getOrderList, stopCharge, orderDeal, orderNotify, Api, orderBatchSettle } from '@/api/business/order'
import YtCrud from '@/components/common/yt-crud.vue'
import {useI18n} from 'vue-i18n'
import {ComponentInternalInstance} from 'vue'
import {ArrowDown} from '@element-plus/icons-vue'
import Settlement from './modules/settlement.vue'
import SettleList from './modules/SettleList.vue'
import Debit from './modules/debit.vue'
import Resettle from './modules/resettle.vue'
import {parseTime} from '@/utils/ruoyi'

import {toDay, weekDay} from '@/utils'
import useAppStore from '@/store/modules/app'
import constants from '@/constants'
import {ElPopconfirm} from 'element-plus'

const appStore = useAppStore()

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { OrderStateEnum, OrderDealEnum } = toRefs<any>(proxy?.useEnum('order_state_enum', 'order_deal_enum'))

const { t, te } = useI18n()

const resettleRef = ref()
const settlementRef = ref()
const settleListRef = ref()
const debitRef = ref()

const state = reactive({
  page: {
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},

})

const shortcuts = [
  {
    text: t('crud.table.search.today'),
    value: () => {
      return toDay()
    },
  },
  {
    text: t('crud.table.search.last7day'),
    value: () => {
      return weekDay(7)
    },
  },
  {
    text: t('crud.table.search.last30day'),
    value: () => {
      return weekDay(30)
    },
  },

]

// 字典
const column = ref<IColumn[]>([
  {
    label: t('business.order.tranId'),
    key: 'tranId',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    colSpan: 22,
  },
  {
    label: t('business.order.userName'),
    key: 'userName',
    align: 'center',
    search: false,
    formHide: false,
    slot: false,
  },
  {
    label: t('business.order.stationName'),
    key: 'stationName',
    type: 'i18nString',
    align: 'center',
    search: false,
    formHide: false,
    slot: false,
  },
  {
    label: t('business.order.chargerDn'),
    key: 'chargerDn',
    align: 'center',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.gunNo'),
    key: 'gunNo',
    align: 'center',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.soc'),
    key: 'soc',
    hide: true,
    align: 'center',
    search: false,
    formHide: false,
    slot: false,
  },
  {
    label: t('business.order.remainMinute'),
    key: 'remainMinute',
    hide: true,
    align: 'center',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.startEndTime'),
    key: 'startEndTime',
    align: 'center',
    hide: false,
    search: false,
    type: 'date',
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.startTime'),
    key: 'startTime',
    align: 'center',
    hide: true,
    search: false,
    type: 'date',
    formHide: false,
    slot: false,
  },

  {
    label: t('business.order.endTime'),
    key: 'endTime',
    align: 'center',
    hide: true,
    search: false,
    type: 'date',
    formHide: false,
    slot: false,
  },
  {
    label: t('business.order.chargeMinute'),
    key: 'chargeMinute',
    align: 'center',
    type: 'number',
    search: false,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.totalQuantity'),
    key: 'totalQuantity',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.totalAmount'),
    key: 'totalAmount',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.parkAmount'),
    key: 'parkAmount',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.orderAmount'),
    key: 'orderAmount',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('business.order.discountAmount'),
    key: 'discountAmount',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    slot: true,
  },

  {
    label: t('business.order.settledAmount'),
    key: 'settledAmount',
    align: 'center',
    search: false,
    sortable: true,
    formHide: false,
    slot: true,
  },

  {
    label: t('business.order.stopReason'),
    key: 'stopReason',
    align: 'center',
    search: false,
    sortable: true,
    formHide: true,
    slot: true,
  },
  {
    label: t('business.order.deal'),
    key: 'deal',
    align: 'center',
    hide: !appStore.profit.enabled,
    search: false,
    sortable: true,
    formHide: false,
    type: 'select',
    componentProps: {
      options: OrderDealEnum,
    },
  },
  {
    label: t('business.order.state'),
    key: 'state',
    align: 'center',
    type: 'select',
    componentProps: {
      options: OrderStateEnum,
      style: {
        width: '120px'
      }
    },
    sortable: true,
    search: true,
    formHide: false,
    slot: true,
  },
  {
    label: t('crud.table.column.createTime'),
    key: 'createTime',
    tableWidth: 180,
    sortable: true,
    type: 'date',
    search: true,
    formHide: false,
    searchSlot: true
  },
  {
    label: t('crud.table.column.note'),
    key: 'note',
    hide: true,
    formHide: false,
    colSpan: 22,
    componentProps: {
      type: 'textarea',
      rows: 2,
    }
  },
])
const crudRef = ref()
const data = ref<any[]>([])
const getData = () => {
  state.loading = true
  getOrderList({
    ...state.page,
    ...state.query,
  })
    .then((res) => {
      data.value = res.data.rows
      state.total = res.data.total
    })
    .finally(() => {
      state.loading = false
    })
}

// 弹窗前置操作
const openBeforeFun = ({ type}) => {
  if (type === 'add') { /* empty */ } else if (type === 'update') { /* empty */ }
}

const handleOperate = (commandObj: any ) => {
  const { command, row } = commandObj
  switch (command) {
    case 'stopCharge':
      handleStopCharge(row)
      break
  }
}

const handleStopCharge = async (row: any) => {
  state.loading = true
  stopCharge(row.id).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleSettle = (row: any) => {
  settlementRef.value.openDialog(row)
}

const handleDebit = (row: any) => {
  debitRef.value.openDialog(row)
}

const handleSettleView = (row: any) => {
  settleListRef.value.openDialog(row)
}

// 导出
const handleExport = () => {
  proxy?.download(Api.export, state.query, `order_${new Date().getTime()}.xlsx`)
}

const handleDeal = async (row: any) => {
  state.loading = true
  orderDeal({ id: row.id}).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleNotify = async (row: any) => {
  state.loading = true
  orderNotify({ id: row.id}).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const handleBatchSettle = () =>{
  state.loading = true
  orderBatchSettle(multipleSelection.value.map(element => element.id)).then(()=>{
    ElMessage.success(t('operate.tooltip.success'))
    getData()
  }).finally(()=>{
    state.loading = false
  })
}

const multipleSelection = ref<any[]>([])

const onChange = (data: any) => {
  multipleSelection.value = data
}



const handleSuccess = ()=>{
  getData()
}



const options = reactive({
  ref: 'crudRef',
  data,
  column,
})
</script>

<style lang="scss" scoped></style>
